<?php

class Zen_Component
{
	private $_b = array();
	
	private $_method_name;
	
	private $_handler_name;
	
	private $_prefixes = array('on', 'after', 'before');
	
	private $_allow_log = true;

	public function detachBehaviors() {
		$this->_b=null;
		return $this;
	}

	public function attachBehavior($handler,$method=null) {
		if (is_array($method)) {
			foreach ($method as $method_one) {
				$this->_attachMethod($handler,$method_one);
			}
		}elseif ($method) {
			$this->_attachMethod($handler,$method);
		}else{
			$handler_methods = get_class_methods($handler);
			foreach ($handler_methods as $h_method) {
				foreach ($this->_prefixes as $prefix) {
					if ( preg_match("/^$prefix/", $h_method) ) {
						$this->_attachMethod($handler,$h_method);
					}
				} 
			}
		}
		return $this;
	}
	
	private function _attachMethod($handler,$method) {
		if (! isset($this->_b[$method]))
			$this->_b[$method] = array();
		$this->_b[$method][]=$handler;
	}
	
	public function detachBehavior($method) {
		if ( isset($this->_b[$method]) ) 
			unset($this->_b[$method]);
		return $this;
	}

	public function raiseBehavior($method, $params = array()) {
		if( isset($this->_b[$method])) {
			foreach($this->_b[$method] as $handler) {
				if(!($handler instanceof Zen_Behavior_Abstract))
					throw new Exception(get_class($handler) . ' is not instanceof class Zen_Behavior');
				if(method_exists($handler,$method))
					$params = $handler->$method($params);
				else
					throw new Exception('Event "' . get_class($this) . '.{' .$name . '" is attached with an invalid handler "{' . $handler[1] . '}".');
				if($handler->isHandled()) break;
			}
		}
		return $params;
	}
	
	public function isAllowLog() {
		return $this->_allow_log;
	}
	
	public function setAllowLog($value) {
		$this->_allow_log = $value;
		return $this;
	}

}	